package com.yaodian100.ec.campaign.web;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.yaodian100.core.common.dao.impl.CommonCriteria;
import com.yaodian100.core.common.utils.DateUtil;
import com.yaodian100.core.common.utils.ServerValue;
import com.yaodian100.core.menu.entity.Menu;
import com.yaodian100.core.menu.service.MenuService;
import com.yaodian100.ec.campaign.entity.CampaignProduct;
import com.yaodian100.ec.campaign.service.CampaignProductService;
import com.yaodian100.ec.common.EcConstant;
import com.yaodian100.ec.common.web.AbstractAction;
import com.yaodian100.ec.product.entity.Product;
import com.yaodian100.ec.product.entity.Specification;
import com.yaodian100.ec.product.service.ProductService;
import com.yaodian100.ec.shelf.entity.Shelf;
import com.yaodian100.ec.shelf.service.ShelfService;

/**
 * @author eric.chen
 * 
 */
public class CampaignProductAction extends AbstractAction {

	private static final long serialVersionUID = 178887580319281383L;

	@Autowired
	private CampaignProductService campaignProductService;
	@Autowired
	private MenuService menuService;
	@Autowired
	private ShelfService shelfService;
	@Autowired
	private ProductService productService;

	/**
	 * 活动集合物件 Campaign Entity List
	 */
	private List<CampaignProduct> campaignList;

	/**
	 * 活动集合物件 Campaign Entity
	 */
	private CampaignProduct campaign;
	/**
	 * 物件识别码
	 */
	private String uuid;
	private String startDate;
	private String startTime;
	private String endDate;
	private String endTime;

	/* 搜寻条件 */
	private BigDecimal paramMinOrderAmount;
	private String paramProductId;
	private Date paramStartDateTime;
	private Date paramEndDateTime;
	private String[] paramEnable = new String[] { "true", "false" };

	/* 选单 */
	private Menu menuMemberRank;
	private Shelf shelf;
	private Product product;

	/* json物件 */
	private String campProductId;
	private Map<String, String> jsonCampMap;

	/**
	 * 載入新增活动資料頁
	 * 
	 * @return
	 */
	public String add() {
		try {
			campaign = new CampaignProduct();
			Calendar cal = DateUtil.getToday();
			cal.add(Calendar.DATE, 7);
			cal.set(Calendar.HOUR_OF_DAY, 0);
			cal.set(Calendar.MINUTE, 0);
			campaign.setStartDateTime(cal.getTime());
			cal.add(Calendar.MONTH, 2);
			campaign.setEndDateTime(cal.getTime());
			campaign.setAllowMemberRank(menuMemberRank.getOptions().keySet().iterator().next());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "edit";
	}

	public String delete() throws Exception {
		try {
			if (campaign == null) {
				addActionError("活动不存在");
				return search();
			}
			campaignProductService.delete(campaign);
		} catch (Exception e) {
			addActionError("删除失败：" + e.getMessage());
			e.printStackTrace();
			return "view";
		}
		return search();
	}

	/**
	 * 修改活动資料
	 * 
	 * @return
	 * @throws Exception
	 */
	public String edit() throws Exception {
		try {
			if (campaign == null) {
				addActionError("活动不存在, 重新选取");
				return search();
			}
			if (StringUtils.isNotBlank(campaign.getProductId())) {
				product = productService.get(campaign.getProductId());
				shelf = shelfService.getActiveShelfByProductId(campaign.getProductId());
				if (null != campaign.getPrice()) {
					campaign.setPrice(campaign.getPrice().setScale(1, BigDecimal.ROUND_FLOOR));
				}
				campaign.setMinOrderAmount(campaign.getMinOrderAmount().setScale(1, BigDecimal.ROUND_FLOOR));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "edit";
	}

	/**
	 * 查询商品名称
	 * 
	 * @return
	 * @throws Exception
	 */
	public String findCampaignProduct() throws Exception {
		jsonCampMap = new HashMap<String, String>();
		if (StringUtils.isNotBlank(campProductId)) {
			Product prod = productService.get(campProductId);
			if (null == prod) {
				jsonCampMap.put("error", "查无此商品");
			} else if (!(prod.getProductType() == 0 || prod.getProductType() == 2 || prod.getProductType() == 3)) {
				jsonCampMap.put("error", "此商品無法被搭选:" + prod.getProductType());
			} else if (prod.getIsDelete().equals("Y")) {
				jsonCampMap.put("error", "此商品已被删除");
			} else if (!prod.getProductStatus().equals("PRD500")) {
				jsonCampMap.put("error", "商品状态不正确:" + prod.getProductStatus());
			} else {
				CommonCriteria criteria = new CommonCriteria();
				criteria.addEq("productId", campProductId);
				criteria.addEq("isDelete", "N");
				List<Specification> specs = productService.getSpecificationList(0, -1, criteria, null);
				if (specs.size() == 0) {
					jsonCampMap.put("error", "此商品无规格");
				} else if (specs.size() > 1) {
					if ("N".equals(ServerValue.getUseDoubleSpec())) {
						jsonCampMap.put("error", "满额购商品只能有一个规格:目前有" + specs.size() + "个规格");
					} else {
						Shelf shelf = shelfService.getActiveShelfByProductId(campProductId);
						if (null != shelf) {
							jsonCampMap.put("productName", prod.getProductName());
							jsonCampMap.put("price", shelf.getShelfPrice().setScale(2).toString());
							jsonCampMap.put("cost", prod.getProductCost().setScale(2).toString());
							jsonCampMap.put("error", "");
						} else {
							jsonCampMap.put("error", "此商品无上架檔资料");
						}
					}
				} else {
					Shelf shelf = shelfService.getActiveShelfByProductId(campProductId);
					if (null != shelf) {
						jsonCampMap.put("productName", prod.getProductName());
						jsonCampMap.put("price", shelf.getShelfPrice().setScale(2).toString());
						jsonCampMap.put("cost", prod.getProductCost().setScale(2).toString());
						jsonCampMap.put("error", "");
					} else {
						jsonCampMap.put("error", "此商品无上架檔资料");
					}
				}
			}
		}
		return "jsonFindCampaignProduct";
	}

	/**
	 * @return the campaign
	 */
	public CampaignProduct getCampaign() {
		return campaign;
	}

	/**
	 * @return the campaignList
	 */
	public List<CampaignProduct> getCampaignList() {
		return campaignList;
	}

	public String getCampProductId() {
		return campProductId;
	}

	/**
	 * @return the endDate
	 */
	public String getEndDate() {
		return endDate;
	}

	/**
	 * @return the endTime
	 */
	public String getEndTime() {
		return endTime;
	}

	public Map<String, String> getJsonCampMap() {
		return jsonCampMap;
	}

	/**
	 * @return the menuMemberRank
	 */
	public Menu getMenuMemberRank() {
		return menuMemberRank;
	}

	/**
	 * @return the paramEnable
	 */
	public String[] getParamEnable() {
		return paramEnable;
	}

	/**
	 * @return the paramEndDateTime
	 */
	public Date getParamEndDateTime() {
		return paramEndDateTime;
	}

	/**
	 * @return the paramName
	 */
	public String getParamMinOrderAmount() {
		if (paramMinOrderAmount != null) {
			return paramMinOrderAmount.toString();
		}
		return "";
	}

	/**
	 * @return the paramProductId
	 */
	public String getParamProductId() {
		return paramProductId;
	}

	/**
	 * @return the paramStartDateTime
	 */
	public Date getParamStartDateTime() {
		return paramStartDateTime;
	}

	public Product getProduct() {
		return product;
	}

	public Shelf getShelf() {
		return shelf;
	}

	/**
	 * @return the startDate
	 */
	public String getStartDate() {
		return startDate;
	}

	/**
	 * @return the startTime
	 */
	public String getStartTime() {
		return startTime;
	}

	/**
	 * @return the uuid
	 */
	public String getUuid() {
		return uuid;
	}

	public String list() throws Exception {
		return "list";
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.ec.common.web.AbstractAction#prepare()
	 */
	@Override
	public void prepare() throws Exception {
		super.prepare();
		if (menuMemberRank == null) {
			menuMemberRank = menuService.get("Member.Rank");
		}
	}

	/**
	 * 储存行销活动资料
	 * 
	 * @return
	 * @throws Exception
	 */
	public String save() throws Exception {
		try {
			if (campaign != null) {
				campaign.setStartDateTime(DateUtil.convertStringToDate(EcConstant.PATTERN_TIMESTAMP_HH_MM, startDate + " "
						+ startTime));
				campaign.setEndDateTime(DateUtil.convertStringToDate(EcConstant.PATTERN_TIMESTAMP_HH_MM, endDate + " "
						+ endTime));
				campaignProductService.save(campaign);
			} else {
				addActionError("活动不存在");
				return search();
			}
		} catch (Exception e) {
			addActionError("储存失败：" + e.getMessage());
			e.printStackTrace();
			return "edit";
		}
		return "view";
	}

	public String search() throws Exception {
		try {
			CommonCriteria cri = new CommonCriteria();
			if (null != paramMinOrderAmount) {
				cri.addLe("minOrderAmount", paramMinOrderAmount);
			}
			if (StringUtils.isNotBlank(paramProductId)) {
				cri.addRlike("productId", paramProductId);
			}
			if (null != paramEndDateTime) {
				cri.addLe("endDateTime", DateUtil.getLastTimestamp(Calendar.DATE, paramEndDateTime));
			}
			if (paramStartDateTime != null) {
				cri.addGe("startDateTime", DateUtil.getFirstTimestamp(Calendar.DATE, paramStartDateTime));
			}
			if (paramEnable != null && paramEnable.length == 1) {
				cri.addEq("enable", Boolean.parseBoolean(paramEnable[0]));
			}
			int entitySize = campaignProductService.getListSize(cri).intValue();
			getPager().setTotalSize(entitySize);
			campaignList = campaignProductService.getList(getPager().getCurrentPage() * getPager().getPageRecord(),
					getPager().getPageRecord(), cri, null);
			int i = 0;
			for (CampaignProduct campaign : campaignList) {
				campaignList.get(i).setMinOrderAmount(campaign.getMinOrderAmount().setScale(1, BigDecimal.ROUND_FLOOR));
				if (null != campaign.getPrice()) {
					campaignList.get(i).setPrice(campaign.getPrice().setScale(1, BigDecimal.ROUND_FLOOR));
				}
				i++;
			}
		} catch (Exception e) {
			addActionError("搜寻失败：" + e.getMessage());
			e.printStackTrace();
		}
		return "list";
	}

	public void setCampProductId(String campProductId) {
		this.campProductId = campProductId;
	}

	/**
	 * @param endDate the endDate to set
	 */
	public void setEndDate(String endDate) {
		this.endDate = endDate;
	}

	/**
	 * @param endTime the endTime to set
	 */
	public void setEndTime(String endTime) {
		this.endTime = endTime;
	}

	public void setJsonCampMap(Map<String, String> jsonCampMap) {
		this.jsonCampMap = jsonCampMap;
	}

	/**
	 * @param paramEnable the paramEnable to set
	 */
	public void setParamEnable(String[] paramEnable) {
		this.paramEnable = paramEnable;
	}

	/**
	 * @param paramEndDateTime the paramEndDateTime to set
	 */
	public void setParamEndDateTime(String d) {
		try {
			if (StringUtils.isNotBlank(d) && d.length() == 10) {
				this.paramEndDateTime = new SimpleDateFormat("yyyy-MM-dd").parse(d);
			}
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @param paramName the paramName to set
	 */
	public void setParamMinOrderAmount(String paramMinOrderAmount) {
		if (StringUtils.isNotBlank(paramMinOrderAmount)) {
			this.paramMinOrderAmount = new BigDecimal(paramMinOrderAmount).setScale(1, BigDecimal.ROUND_FLOOR);
		} else {
			this.paramMinOrderAmount = null;
		}
	}

	/**
	 * @param paramProductId the paramProductId to set
	 */
	public void setParamProductId(String paramProductId) {
		this.paramProductId = paramProductId;
	}

	/**
	 * @param paramStartDateTime the paramStartDateTime to set
	 */
	public void setParamStartDateTime(String d) {
		try {
			if (StringUtils.isNotBlank(d) && d.length() == 10) {
				this.paramStartDateTime = new SimpleDateFormat("yyyy-MM-dd").parse(d);
			}
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void setProduct(Product product) {
		this.product = product;
	}

	/**
	 * @param startDate the startDate to set
	 */
	public void setStartDate(String startDate) {
		this.startDate = startDate;
	}

	/**
	 * @param startTime the startTime to set
	 */
	public void setStartTime(String startTime) {
		this.startTime = startTime;
	}

	/**
	 * @param uuid the uuid to set
	 */
	public void setUuid(String uuid) {
		this.uuid = uuid;
	}

	/**
	 * 檢視活动資料
	 * 
	 * @return
	 */
	public String view() throws Exception {
		try {
			if (StringUtils.isNotBlank(uuid)) {
				campaign = campaignProductService.get(uuid);
			}
			if (campaign == null) {
				addActionError("活动UUID 有误, 重新选取");
				return search();
			}
			if (StringUtils.isNotBlank(campaign.getProductId())) {
				product = productService.get(campaign.getProductId());
				campaign.setMinOrderAmount(campaign.getMinOrderAmount().setScale(1, BigDecimal.ROUND_FLOOR));
				if (null != campaign.getPrice()) {
					campaign.setPrice(campaign.getPrice().setScale(1, BigDecimal.ROUND_FLOOR));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "view";
	}
}